const { app, server } = require('./src/app');
const logger = require('./src/utils/logger');
const { connectDB } = require('./src/config/database');
const models = require('./src/models'); // 加载模型关联

// 连接数据库
connectDB();

const PORT = process.env.PORT || 3000;

// 启动服务器
const httpServer = server.listen(PORT, () => {
  logger.info(`宠物护理后端服务已启动，端口: ${PORT}`);
  logger.info(`环境: ${process.env.NODE_ENV || 'development'}`);
  logger.info(`API文档: http://localhost:${PORT}/api-docs`);
});

// 优雅关闭
process.on('SIGTERM', () => {
  logger.info('收到SIGTERM信号，正在关闭服务器...');
  httpServer.close(() => {
    logger.info('服务器已关闭');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  logger.info('收到SIGINT信号，正在关闭服务器...');
  httpServer.close(() => {
    logger.info('服务器已关闭');
    process.exit(0);
  });
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  logger.error('未捕获的异常:', err);
  process.exit(1);
});

process.on('unhandledRejection', (err) => {
  logger.error('未处理的Promise拒绝:', err);
  httpServer.close(() => {
    process.exit(1);
  });
});

module.exports = httpServer;